import os

from django.core.paginator import Paginator
from django.shortcuts import render

from . import models

# Create your views here.

def index(request):
    lead = models.Game.objects.filter(top=True)
    hot = models.Game.objects.order_by("-touched", "-downloaded")[:4]
    news = models.Game.objects.order_by("-gamedown__last_time", "-touched")[:4]
    game_class = models.GameClass.objects.filter(top=True)
    context = {}
    context['path'] = request.path.strip('/').split('/')[1]
    context['lead'] = lead
    context['hot'] = hot
    context['news'] = news
    context['game_class'] = game_class
    return render(request, 'web_index.html', context)


def web_login(request):
    return render(request, 'web_login.html')


def web_register(request):
    return render(request, 'web_register.html')


def web_detail(request):
    hot = models.Game.objects.order_by("-touched", "-downloaded")
    hot_pag = Paginator(hot, 5)
    hots = hot_pag.page(request.GET.get("hot_page"))
    new = models.Game.objects.order_by("-gamedown__last_time", "-touched")
    news_pag = Paginator(new, 5)
    news = news_pag.page(request.GET.get("hot_page"))
    context = {}
    context['path'] = request.path.strip('/').split('/')[1]
    context['hots'] = hots
    context['news'] = news
    return render(request, 'web_detail.html', context=context)


def game_more(request):
    return render(request, 'game_more.html')


def game_main(request):
    class_id = request.GET.get('class_id')

    if class_id:
        game_class = models.GameClass.objects.filter(id=class_id)
        pass
    else:
        game_class = models.GameClass.objects.filter(top=True)
        pass

    hots = models.Game.objects.order_by("-touched", "-downloaded")[:6]
    new_ups = models.Game.objects.order_by("-gamedown__last_time")[:6]
    # for nw in new_ups:
    #     print((nw.belong_class.all().first()))
    context = {}
    context['path'] = request.path.strip('/').split('/')[1]
    context['game_class'] = game_class[:10]
    context['hots'] = hots[:10]
    context['new_ups'] = new_ups[:10]
    return render(request, 'game_main.html', context)


def game_detail(request):
    game_id = request.GET.get('id')
    game = models.Game.objects.get(id=game_id)
    if game.gamedown.android:
        app_path = os.path.join(os.getcwd(), 'upload/'+str(game.gamedown.android))
    else:
        app_path = os.path.join(os.getcwd(), 'upload/' + str(game.gamedown.ios))
    size = os.path.getsize(app_path)
    context = {}
    context['game'] = game
    context['size'] = size
    return render(request, 'game_detail.html', context)


